#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>

#include "exec.h"

static gboolean  exec_waitpid_timer(gpointer data)
{
	//printf("~~~%s\n" ,__FUNCTION__);
	Exec *exec=data;
	int status;
	pid_t w;
	if(waitpid(exec->pid,&status,WNOHANG)>0){
		printf("~~~%s\n" ,__FUNCTION__);
		exec->finished_func(exec,exec->user_data);
		return FALSE;
	}
	return TRUE;	
}

static pid_t exec_do(Exec *exec)
{
	printf("~~~%s\n" ,__FUNCTION__);
	pid_t pid=fork();
	if(pid==-1)
	{
		fprintf(stderr,"%s:fork error",__FUNCTION__);
		exit(-1);
	}
	else if(pid==0)
	{
		execvp(exec->cmd,exec->argv);
		printf("fdfdfdfdfdfdf\n");
		exit( -1);
	}
	else
	{
		exec->pid=pid;
		exec->timer=g_timeout_add(200,exec_waitpid_timer,exec);
	}
	printf("%d\n" ,exec->pid);
	return exec->pid;
	
}



///////////////////////////////////////////////////

Exec *exec_create(const char* cmd,int argc,char **argv,gboolean stop_music,
				 gboolean (*func)(Exec* exec,gpointer data),
				gpointer user_data)
{
	Exec *exec;
	
	if(!cmd||argc<1||!func)
		return NULL;
	
	exec = (Exec *)g_malloc0(sizeof(Exec)+1);
	
	exec->cmd=strdup(cmd);
	exec->argc=argc;
	exec->argv=argv;
	exec->stop_music=stop_music;
	exec->finished_func=func;
	exec->user_data=user_data;
	
	if(exec_do(exec)<=0)
	{
		exec_destroy(exec);
		return NULL;
	}
	
	return exec;
}

void exec_destroy(Exec *exec)
{
	printf("~~~%s\n" ,__FUNCTION__);
	if(exec->pid)
		kill(exec->pid,9);//FIXME
	if(exec->timer)
		g_source_remove(exec->timer);
	free(exec->cmd);
	free(exec);
}
